package JoReg

import "fmt"

type Lexer struct {
	tokenSlc   []Token
	tokenIndex int
}

func MakeLexer() *Lexer {
	return &Lexer{}
}

// Parse token解析
func (this *Lexer) ParseToken(express string) {
	charSlc := []byte(express)
	tokenSlc := make([]Token, 0)
	var token Token
	for _, char := range charSlc {
		switch char {
		case SEMI:
			token = NewSemiToken()
		case 48, 49, 50, 51, 52, 53, 54, 55, 56, 57:
			token = NewNumberToken(char)
		case DOT:
			token = NewDotToken()
		case ASTERISK:
			token = NewAsteriskToken()
		case PLUS:
			token = NewPlusToken()
		case OR:
			token = NewOrToken()
		case OPTION:
			token = NewOptionToken()
		case OPEN_PAREN:
			token = NewOpenParenToken()
		case CLOSE_PAREN:
			token = NewCloseParenToken()
		case OPEN_BRACKET:
			token = NewOpenBracketToken()
		case CLOSE_BRACKET:
			token = NewCloseBracketToken()
		case OPEN_CURLY:
			token = NewOpenCurlyToken()
		case CLOSE_CURLY:
			token = NewCloseCurlyToken()
		default:
			token = NewCharacterToken(char)
		}
		tokenSlc = append(tokenSlc, token)
	}
	this.tokenSlc = tokenSlc
	this.tokenIndex = 0
}

func (this *Lexer) lookahead() Token {
	if this.tokenIndex+1 >= len(this.tokenSlc) {
		return NewEosToken()
	}
	return this.tokenSlc[this.tokenIndex+1]
}

func (this *Lexer) advance() Token {
	if this.tokenIndex >= len(this.tokenSlc) {
		return NewEosToken()
	}
	this.tokenIndex++
	return this.tokenSlc[this.tokenIndex-1]
}

func (this *Lexer) curToken() Token {
	if this.tokenIndex >= len(this.tokenSlc) {
		return NewEosToken()
	}
	return this.tokenSlc[this.tokenIndex]
}

func (this *Lexer) matchToken(matchToken byte) bool {
	if this.tokenIndex >= len(this.tokenSlc) {
		return false
	}
	curToken := this.tokenSlc[this.tokenIndex]
	if curToken.token == matchToken {
		return true
	} else {
		return false
	}
}

func (this *Lexer) isEos() bool {
	if this.curToken().token == EOS {
		return true
	}
	return false
}

func (this *Lexer) print() {
	for _, token := range this.tokenSlc {
		fmt.Printf("token: %c, lexeme:%c\n", token.token, token.lexeme)
	}
}
